#!/bin/python
import csv
import numpy as np
from scipy.optimize import leastsq
import matplotlib.pyplot as plt

with open('dlt.csv') as f:
    reader = csv.reader(f)
    next(reader)
    dlt = np.array(list(reader)).astype(np.float)[5000:]
    Dts, count, PWM, curr, volt, Res = dlt.transpose()
    Dts -= Dts[0]
    PWM = 255-PWM

with open('flir.csv') as f:
    reader = csv.reader(f)
    next(reader)
    flir = np.array(list(reader)).astype(np.float)
    Fts, temp = flir.transpose()
    Fts -= Fts[0]


def meaure_C(n=5000):
    """
    利用断电后降温曲线测量时间常数
    """
    Fts2=Fts[-n:]
    temp2=temp[-n:]
    def func(p,x):
        c, tau, y0 = p
        return c*np.exp(-x/tau) + y0
    def error(p,x,y):
        return func(p, x) - y
    p0 = [200, 200, 30]
    c,t,y0=leastsq(error, p0, args=(Fts2, temp2))[0]
    plt.plot(flir[:,0], flir[:,1])
    plt.show()

def calib_I(n1=600, n2=1000):
    """
    校准电流补偿，线性拟合PWM和电流关系
    """
    plt.plot(PWM, c='b')
    plt.twinx()
    plt.plot(curr, c='g')
    plt.show()
    k,b = leastsq(lambda p,x,y:y-(p[0]*x+p[1]), (0,0), args=(PWM[n1:n2], curr[n1:n2]))[0]
    return b

R=PWM*volt/(curr+2650)
R2=np.clip(R, np.percentile(R, 15), np.percentile(R, 95))
plt.plot(Dts, R2, c='g')
#plt.plot(Dts, PWM, c='b')
plt.twinx()
temp2=np.clip(temp, np.percentile(R, 3), None)
plt.plot(Fts, temp2, c='r')
plt.show()
